<template>
  <div class="container">
    <Breadcrumb :items="['menu.list', 'menu.promotion.column.list']" />
    <a-card class="general-card" :title="$t('menu.promotion.column.list')">

      <!-- 头部区域 -->
      <div class="header">
        <!-- 搜索栏 -->
        <div v-if="showQuery" class="header-query">
          <a-form ref="queryRef" :model="queryParams" layout="inline">
            <a-form-item field="name" hide-label>
              <a-input
                  v-model="queryParams.columnName"
                  placeholder="输入专栏名或描述进行搜索"
                  allow-clear
                  style="width: 200px"
                  @press-enter="handleQuery"
              />
            </a-form-item>

            <a-form-item hide-label>
              <a-space>
                <a-button type="primary" @click="handleQuery">
                  <template #icon><icon-search /></template>查询
                </a-button>
                <a-button @click="resetQuery">
                  <template #icon><icon-refresh /></template>重置
                </a-button>
              </a-space>
            </a-form-item>
          </a-form>
        </div>
        <!-- 操作栏 -->
        <div class="header-operation">
          <a-row>
            <a-col :span="16">
              <a-space>
                <a-button v-permission="['promotion:column:add']" type="primary" @click="toAdd">
                  <template #icon><icon-plus/></template>新增
                </a-button>

                <a-button
                    v-permission="['promotion:column:update']"
                    type="primary"
                    status="success"
                    :disabled="single"
                    :title="single ? '请选择一条要修改的数据' : ''"
                    @click="toUpdate(checkedIds[0])"
                >
                  <template #icon><icon-edit /></template>修改
                </a-button>
                <a-button
                    v-permission="['promotion:column:delete']"
                    type="primary"
                    status="danger"
                    :disabled="multiple"
                    :title="multiple ? '请选择要删除的数据' : ''"
                    @click="handleBatchDelete"
                >
                  <template #icon><icon-delete /></template>删除
                </a-button>
                <a-button
                    v-permission="['promotion:column:export']"
                    :loading="exportLoading"
                    type="primary"
                    status="warning"
                    @click="handleExport"
                >
                  <template #icon><icon-download /></template>导出
                </a-button>
              </a-space>
            </a-col>
            <a-col :span="8">
              <right-toolbar v-model:show-query="showQuery" @refresh="fetchData"/>
            </a-col>
          </a-row>
        </div>
      </div>


      <a-table
          row-key="id"
          :data="columnList"
          :loading="loading"
          :pagination="{
              showTotal: true,
              showPageSize: true,
              total: total,
              current: queryParams.page,
            }"
          :bordered="false"
          :size="size"
          @page-change="handlePageChange"
          @page-size-change="handlePageSizeChange"
          @selection-change="handleSelectionChange"
          :row-selection="{
              type: 'checkbox',
              showCheckedAll: true,
              onlyCurrent: false,
            }"
      >

        <template #columns>
          <a-table-column title="ID" data-index="id" :width="30" />
          <a-table-column title="专栏名" :width="80">
            <template #cell="{ record }">
              <a-link @click="toDetail(record.id)">{{
                  record.name
                }}</a-link>
            </template>
          </a-table-column>

          <a-table-column title="专栏描述" data-index="descs" :width="100" />

          <a-table-column title="入口图片" align="center" :width="50">
            <template #cell="{ record }">
              <img :width="120" :height="60" :src="record.enterImg" alt="入口图片" />
            </template>
          </a-table-column>

          <a-table-column title="内部图片" align="center" :width="50">
            <template #cell="{ record }">
              <img :width="120" :height="60" :src="record.bannerImg" alt="内部图片" />
            </template>
          </a-table-column>

          
          <a-table-column title="状态" :width="100">
            <template #cell="{ record }">
              <span v-if="record.status === 0">下线</span>
              <span v-else-if="record.status === 1">上线</span>
              <span v-else>未知</span>
            </template>
          </a-table-column>

          <a-table-column title="点击数" data-index="clickCount" :width="100" />
          <a-table-column title="排序" data-index="sort" :width="100" />

          <a-table-column title="创建时间" :width="100">
            <template #cell="{ record }">
              {{ record.createdAt }}
            </template>
          </a-table-column>

          <a-table-column title="操作" align="center" fixed="right" :width="100">

            <template #cell="{ record }">


              <a-button
                  v-permission="['promotion:column:update']"
                  type="text"
                  size="small"
                  title="修改"
                  @click="toUpdate(record.id)"
              >
                <template #icon><icon-edit /></template>修改
              </a-button>

              <a-popconfirm
                  content="确定删除吗？"
                  type="warning"
                  @ok="handleDelete([record.id])"
              >
                <a-button
                    v-permission="['promotion:column:delete']"
                    type="text"
                    size="small"
                    title="删除"
                    :disabled="record.disabled"
                >
                  <template #icon><icon-delete /></template>删除
                </a-button>
              </a-popconfirm>
            </template>

          </a-table-column>
        </template>


      </a-table>
    </a-card>




    <!-- 表单区域 -->
    <a-drawer :title="title" :visible="visible" :width="690" :mask-closable="false" unmount-on-close
        render-to-body @ok="handleOk" @cancel="handleCancel"
    >
    <a-form ref="formRef" :model="columnSaveForm" :rules="rules" :label-col-style="{ width: '94px' }"
          size="large" layout="inline" auto-label-width >

        <a-form-item label="专栏名" field="columnName">
          <a-input
              v-model="columnSaveForm.name"
              placeholder="请输入专栏名"
              style="width: 500px"
          />
        </a-form-item>

        <a-form-item label="专栏描述" field="descs">
          <a-input
              v-model="columnSaveForm.descs"
              placeholder="请输入专栏描述"
              style="width: 500px"
          />
        </a-form-item>


        <a-form-item label="轮播图片" field="pic">
          <a-upload :custom-request="handleUploadEnter" style="width: 500px;" />
        </a-form-item>

        <a-form-item label="轮播图片" field="pic">
          <a-upload :custom-request="handleUploadBanner" style="width: 500px;" />
        </a-form-item>

        <a-form-item label="上下线状态" field="type">
          <a-radio-group v-model="columnSaveForm.status">
            <a-radio :value="0">下线</a-radio>
            <a-radio :value="1">上线</a-radio>
          </a-radio-group>
        </a-form-item>

        <a-form-item label="点击数" field="clickCount">
          <a-input
              v-model="columnSaveForm.clickCount"
              placeholder="请输入点击数"
              style="width: 500px"
          />
        </a-form-item> 

        <a-form-item label="排序" field="sort">
          <a-input
              v-model="columnSaveForm.sort"
              placeholder="请输入排序序号"
              style="width: 500px;"
          />
        </a-form-item>

      </a-form>
    </a-drawer>


    <a-drawer
        title="专栏详情"
        :visible="detailVisible"
        :width="700"
        :footer="false"
        unmount-on-close
        render-to-body
        @cancel="handleDetailCancel"
    >
      <a-descriptions :column="1" bordered size="large">

        <a-descriptions-item label="专栏名">
          <a-skeleton v-if="detailLoading" :animation="true">
            <a-skeleton-line :rows="1" />
          </a-skeleton>
          <span v-else>{{ column.name }}</span>
        </a-descriptions-item>

        <a-descriptions-item label="专栏描述">
          <a-skeleton v-if="detailLoading" :animation="true">
            <a-skeleton-line :rows="1" />
          </a-skeleton>
          <span v-else>{{ column.descs }}</span>
        </a-descriptions-item>

        <a-descriptions-item label="入口图片">
          <a-skeleton v-if="detailLoading" :animation="true">
            <a-skeleton-line :rows="1" />
          </a-skeleton>
          <span v-else><img :width="480" :src="column.enterImg" alt="活动图" /></span>
        </a-descriptions-item>

        <a-descriptions-item label="内部图片">
          <a-skeleton v-if="detailLoading" :animation="true">
            <a-skeleton-line :rows="1" />
          </a-skeleton>
          <span v-else>{{ column.bannerImg }}</span>
        </a-descriptions-item>

        <a-descriptions-item label="上下线状态">
          <a-skeleton v-if="detailLoading" :animation="true">
            <a-skeleton-line :rows="1" />
          </a-skeleton>
          <span v-else>{{ column.status }}</span>
        </a-descriptions-item>


        <a-descriptions-item label="点击数">
          <a-skeleton v-if="detailLoading" :animation="true">
            <a-skeleton-line :rows="1" />
          </a-skeleton>
          <span v-else>{{ column.clickCount }}</span>
        </a-descriptions-item>
        
        <a-descriptions-item label="排序">
          <a-skeleton v-if="detailLoading" :animation="true">
            <a-skeleton-line :rows="1" />
          </a-skeleton>
          <span v-else>{{ column.sort }}</span>
        </a-descriptions-item>

        <a-descriptions-item label="创建者">
          <a-skeleton v-if="detailLoading" :animation="true">
            <a-skeleton-line :rows="1" />
          </a-skeleton>
          <span v-else>{{ column.createdBy }}</span>
        </a-descriptions-item>


        <a-descriptions-item label="更新者">
          <a-skeleton v-if="detailLoading" :animation="true">
            <a-skeleton-line :rows="1" />
          </a-skeleton>
          <span v-else>{{ column.updatedBy }}</span>
        </a-descriptions-item>

        <a-descriptions-item label="创建时间">
          <a-skeleton v-if="detailLoading" :animation="true">
            <a-skeleton-line :rows="1" />
          </a-skeleton>
          <span v-else>{{ column.createdAt }}</span>
        </a-descriptions-item>

        <a-descriptions-item label="更新时间">
          <a-skeleton v-if="detailLoading" :animation="true">
            <a-skeleton-line :rows="1" />
          </a-skeleton>
          <span v-else>{{ column.updatedAt }}</span>
        </a-descriptions-item>


      </a-descriptions>
    </a-drawer>

  </div>



</template>

<script lang="ts" setup>
  import {getCurrentInstance, reactive, ref, toRefs} from 'vue';
  import {useI18n} from 'vue-i18n';
  import useLoading from '@/hooks/loading';
  import {PolicyRecord} from '@/api/list';
  import {
    addColumn,
    getColumn,
    updateColumn,
    deleteColumn,
    ColumnSaveCommand,
    ColumnParam,
    ColumnResponse,
    pageColumn
  } from "@/api/promotion/column";
  import { FileItem, RequestOption } from '@arco-design/web-vue';
  import { uploadFile } from "@/api/file/file";

  import { onBeforeUnmount, shallowRef } from 'vue'
  import { Boot } from '@wangeditor/editor'
  import markdownModule from '@wangeditor/plugin-md'


  const showQuery = ref(true);
  Boot.registerModule(markdownModule)




  type SizeProps = 'mini' | 'small' | 'medium' | 'large';
  const { proxy } = getCurrentInstance() as any;
  const { loading, setLoading } = useLoading(true);
  const { t } = useI18n();
  const renderData = ref<PolicyRecord[]>([]);

  const size = ref<SizeProps>('medium');
  const checkedIds = ref<Array<number>>([]);
  const title = ref('');
  const single = ref(true);
  const multiple = ref(true);

  const data = reactive({
    queryParams: {
      columnName: undefined,
      page: 1,
      size: 10,
      sort: ['createdAt,desc'],
    },
    columnSaveForm: {} as ColumnSaveCommand,
    rules: {
      username: [{ required: true, message: '请输入管理员专栏名' }],
      password: [{ required: true, message: '请输入管理员密码' }]
    },

  });
  const { queryParams, columnSaveForm, rules } = toRefs(data);

  const columnList = ref<ColumnResponse[]>([]);
  const total = ref(0);

  const column = ref<ColumnResponse>({
    id: undefined,
    name: '',
    descs: '',
    enterImg: '',
    bannerImg: '',
    status: undefined,
    clickCount: undefined,
    sort: undefined,

    createdBy: '',
    updatedBy: '',
    createdAt: '',
    updatedAt: ''
  });

  const fetchData = (params: ColumnParam = {...queryParams.value}) => {
    setLoading(true);
    pageColumn(params).then(res => {
      columnList.value = res.data.list;
      total.value = Number(res.data.total);
    }).finally(() => {
      setLoading(false);
    });

  };

  fetchData();
  const reset = () => {
    columnSaveForm.value = {
      id: undefined,
      name: '',
      descs: '',
      enterImg: '',
      bannerImg: '',
      status: undefined,
      clickCount: undefined,
      sort: undefined,
    };
    proxy.$refs.formRef?.reserFields();
  };

  const visible = ref(false);
  const toAdd = () => {
    reset();
    title.value = '新增专栏';
    visible.value = true;
  };


  const toUpdate = (id: number) => {
    reset();
    getColumn(id).then((res) => {
      columnSaveForm.value = res.data as unknown as ColumnSaveCommand;
      title.value = '修改专栏';
      visible.value = true;
    });
  };

  const handleUploadBanner = (options: RequestOption) => {
    const controller = new AbortController();
    (async function requestWrap() {
      const {
        onProgress,
        onError,
        onSuccess,
        fileItem,
        name = 'file',
      } = options;
      onProgress(20);
      const formData = new FormData();
      formData.append(name as string, fileItem.file as Blob);
      uploadFile(formData)
        .then((res) => {
          onSuccess(res);
          columnSaveForm.value.bannerImg = res.data;
          proxy.$message.success("上传成功");
        })
        .catch((error) => {
          onError(error);
        });
    })();
    return {
      abort() {
        controller.abort();
      },
    };
  };


  const handleUploadEnter = (options: RequestOption) => {
    const controller = new AbortController();
    (async function requestWrap() {
      const {
        onProgress,
        onError,
        onSuccess,
        fileItem,
        name = 'file',
      } = options;
      onProgress(20);
      const formData = new FormData();
      formData.append(name as string, fileItem.file as Blob);
      uploadFile(formData)
        .then((res) => {
          onSuccess(res);
          columnSaveForm.value.enterImg = res.data;
          proxy.$message.success("上传成功");
        })
        .catch((error) => {
          onError(error);
        });
    })();
    return {
      abort() {
        controller.abort();
      },
    };
  };


  const handleQuery = () => {
    console.log("handleQuery", queryParams);
    fetchData();
  };

  const resetQuery = () => {
    proxy.$refs.queryRef.resetFields();
    handleQuery();
  };

  const handlePageChange = (current: number) => {
    queryParams.value.page = current;
    fetchData();
  };

  const handlePageSizeChange = (pageSize: number) => {
    queryParams.value.size = pageSize;
    fetchData();
  };

  const handleSelectionChange = (rowKeys: Array<any>) => {
    checkedIds.value = rowKeys;
    single.value = rowKeys.length !== 1;
    multiple.value = !rowKeys.length;
  };


  const handleCancel = () => {
    visible.value = false;
    proxy.$refs.formRef?.resetFields();
    proxy.$refs.userRoleFormRef?.resetFields();
  };

  const handleOk = () => {
    proxy.$refs.formRef.validate((valid: any) => {
      if (!valid) {
        if (columnSaveForm.value.id !== undefined) {
          updateColumn(columnSaveForm.value).then((res:any) => {
            handleCancel();
            fetchData();
            proxy.$message.success(res.message);
          });
        } else {
          addColumn(columnSaveForm.value).then((res:any) => {
            handleCancel();
            fetchData();
            proxy.$message.success(res.message);
          });
        }
      }
    });
  };

  const handleDelete = (ids: Array<number>) => {
    deleteColumn(ids).then((res:any) => {
      proxy.$message.success(res.message);
      fetchData();
    });
  };

  const detailLoading = ref(false);
  const detailVisible = ref(false);
  const toDetail = async (id: number) => {
    if (detailLoading.value) return;
    detailLoading.value = true;
    detailVisible.value = true;
    getColumn(id)
        .then((res) => {
          column.value = res.data;
        })
        .finally(() => {
          detailLoading.value = false;
        });
  };

  const handleDetailCancel = () => {
    detailVisible.value = false;
  };

  const handleBatchDelete = () => {
    if(checkedIds.value.length === 0) {
      proxy.$message.info('没有选中数据');
    }else {
      proxy.$modal.warning({
        title: '警告',
        titleAlign: "start",
        content: '确定删除吗？',
        hideCancel: false,
        onOk: () => {
          handleDelete(checkedIds.value);
        }
      });
    }
  }

  const exportLoading = ref(false);
  const handleExport = () => {
    if(exportLoading.value) return;

    exportLoading.value = true;
    proxy
        .download('/admin/promotion/column/export', { ...queryParams.value }, '专栏数据')
        .finally(() => {
          exportLoading.value = false;
        });

  }




  // 编辑器实例，必须用 shallowRef
  const editorRef = shallowRef()

  const editorConfig = { placeholder: '请输入内容...' }

  // 专栏销毁时，也及时销毁编辑器
  onBeforeUnmount(() => {
      const editor = editorRef.value
      if (editor == null) return
      editor.destroy()
  })



</script>

<script lang="ts">
export default {
  name: 'SearchTable'
};
</script>

<style scoped lang="less">
.container {
  padding: 0 20px 20px 20px;
}

.header {
  padding-bottom: 10px;
}
</style>
